<?php

class weixinController
{

	public $data = array();
	private $access_token = ''; 
	public $follower = array();
	
	public function __construct()
	{
		$this->getTextMsg();
	}
	
	/**
	 * 错误报告
	 * @param unknown $content
	 */
	public function errorlog($content)
   	{
    	$fp = fopen("error.txt","w");
    	fwrite($fp,$content);
    	fclose($fp);
   	}
   	
   	/**
   	 * 获取access_token
   	 * @param $appid
   	 * @param $secret
   	 * @return
   	 */
   	public function getToken($appid, $secret)
  	{
   		$url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$secret;
   		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		$result = curl_exec($ch);

   		$token = json_decode($result);
   	
   		$yf_info['access_token'] = $this->access_token=$token->access_token;
   		$yf_info['expires_in'] = $token->expires_in;		
   		return $yf_info;
   	}
   	
   	/**
   	 * 设置access_token
   	 * @param $access_token
   	 */
   	public function setToken($access_token)
   	{
   		$this->access_token = $access_token;
   	}
   	
   	/**
   	 * 验证服务器地址的有效性
   	 * @param unknown $token
   	 * @return boolean
   	 */
   	private function checkSignature($token)
   	{
   		$signature = $_GET["signature"];
   		$timestamp = $_GET["timestamp"];
   		$nonce = $_GET["nonce"];
   		$tmpArr = array($token, $timestamp, $nonce);
   		sort($tmpArr);
   		$tmpStr = implode( $tmpArr );
   		$tmpStr = sha1( $tmpStr );
   		if($tmpStr == $signature ){
   			return true;
   		}else{
   			return false;
   		}
   	}
	
   	/**
   	 * 网页授权
   	 * @param unknown $appid
   	 * @param unknown $secret
   	 * @param unknown $code
   	 * @return mixed
   	 */
   	public function getUserByCode($appid, $secret, $code)
   	{
   		$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$secret&code=$code&grant_type=authorization_code";
   		$json = file_get_contents($url);
   		$arr = json_decode($json,true);
   		return $arr;
   	}
   	
   	/**
   	 * 获取用户信息(授权)
   	 * @param $openid
   	 * @param string $access_token
   	 * @return mixed
   	 */
   	public function getUserInfo($openid, $access_token = '')
   	{
   		if($access_token == '')
   		{
   			$access_token = $this->access_token;
   		}
   		$url = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid&lang=zh_CN";
   		$json = file_get_contents($url);//获取微信用户基本信息
   		$arr = json_decode($json,true);
   		return $arr;
	}
	
	/**
	 * 获取用户信息(订阅号也是用授权)
	 */
	public function getUserInfo_simple($openid, $access_token = '')
	{
		if($access_token == '')
		{
			$access_token = $this->access_token;
		}
		$url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$access_token&openid=$openid&lang=zh_CN";
		$json = file_get_contents($url);//获取微信用户基本信息
		$arr = json_decode($json,true);
		return $arr;
	}
	
	
	
	
	/**
	 * 用post方法获取数据
	 * @param $url
	 * @param $data
	 * @return
	 */
   	public function post_it($url, $data)
   	{
   	  	$curl = curl_init();
   	  	curl_setopt($curl, CURLOPT_URL, $url);
   	  	curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
      	curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
   	  	curl_setopt($curl, CURLOPT_POST, 1);
   	  	curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
   	  	curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
     	$result = curl_exec($curl);
   	   	if(curl_errno($curl)) 
   	   	{
   			return 'Errno'.curl_error($curl);
   	    }
   	  	curl_close($curl);
   	   	return $result;
   	}
   	
   	/**
   	 * 用get方法获取数据
   	 * @param unknown $url
   	 * @return mixed
   	 */
   	public function get_it($url)
   	{
   	 	$ch = curl_init();
   	  	curl_setopt($ch, CURLOPT_URL, $url);
   	  	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
   	  	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
   	  	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
   	  	$result = curl_exec($ch);
   	  	return $result ;
   	}
   
   	/**
   	 * 获取关注列表
   	 * @param string $token
   	 * @return multitype:
   	 */
   	public function getFollower($token = '')
   	{
   		$this->access_token = $token == '' ? $this->access_token : $token;
   		if($this->access_token != '')
   	  	{
   	  		$url = 'https://api.weixin.qq.com/cgi-bin/user/get?access_token='.$this->access_token.'';
        	$result = $this->get_it($url);

   	  		$data = json_decode($result);
   	  		$data = (array)$data;
   	  	
   	  		$this->follower = $data[data];
   	  		$this->follower = $this->follower->openid;
   	  	}
   	  	return $this->follower;
   	}
   
   	/**
   	 * 检验token名称是否合法
   	 * @param unknown $token
   	 * @return unknown
   	 */
	public function valid($token)
	{
		$echoStr = $_GET["echostr"];
		if($this->checkSignature($token)){
			return $echoStr;
		}
	}
	
	/**
	 * 客服接口,回复图文信息
	 * @param $openid
	 * @param $arr
	 * @param string $token
	 */
    public function sendImgMsg($openid, $arr, $token = '')
    {
    	$this->access_token = $token == '' ? $this->access_token : $token;
    	$img_array = array(
    					'touser'=>$openid,
    					'msgtype'=>'news',
    					'news'=>''
    				);

    	$img_array['news']['articles'] = $arr;
    	$data = urldecode(json_encode($img_array));
  
    	if($this->access_token != '')
    	{
    		$url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$this->access_token;
    		$this->post_it($url, $data);
    	}
    }

    /**
     * 创建自定义菜单
     * @param $data
     * @param string $token
     * @return Ambigous <string, mixed>
     */
    public function create_menu($data, $token = '')
    {
    	$result = '';
    	$this->access_token = $token == '' ? $this->access_token : $token;
    	if($this->access_token != '')
    	{
    		$url = 'https://api.weixin.qq.com/cgi-bin/menu/create?access_token='.$this->access_token;
    	   	$result = $this->post_it($url, $data);
    	}
    	return $result;
    }
    
    /**
     * 获取自定义菜单
     * @param $token
     * @return 
     */
    public function get_menu($token = '')
    {
    	$result = '';
    	$this->access_token = $token == '' ? $this->access_token : $token;
    	if($this->access_token != '')
    	{
    	   $url = "https://api.weixin.qq.com/cgi-bin/menu/get?access_token=".$this->access_token;
    	   $result = $this->get_it($url);
    	}
    	return $result;
    }
    
    /**
     * 删除自定义菜单
     * @param string $token
     * @return Ambigous <string, mixed>
     */
    
    public function del_menu($token = '')
    {
    	$result = '';
    	$this->access_token = $token == '' ? $this->access_token : $token;
    	if($this->access_token != '')
    	{
    		$url = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=".$this->access_token;
    		$result = $this->get_it($url);
    	}
    	return $result;
    }
    
    /**
     * 群发消息
     * @param $data
     * @param $type
     * @param $token
     */
    public function send_to_all($data, $type, $token = '')
    {
    	$this->access_token = $token == '' ? $this->access_token : $token;
    	if($this->access_token != '')
    	{
    		$follower = $this->getFollower();
    		if($type == 'text')
    	  	{
    	  		if(count($follower) > 0)
    	  		{
    	  	    	foreach($follower as $k=>$v)
    	  	   		{
    	  	   	  		$this->sendTextMsg($v,$data);
    	  	   		}
    	  		}	
    	  	}
    	  	else if($type=='image')
    	  	{
    	  		if(count($follower) > 0)
    	  		{
    	  			foreach($follower as $k => $v)
    	  			{
    	  				$this->sendImgMsg($v, $data);
    	  			}
    	  		}
    	  	}
    	}
    }
    
    /**
     * 客服接口,回复文本信息
     * @param $openid
     * @param $text
     * @param $token
     */
   	public function sendTextMsg($openid, $text, $token)
    {
    	$data = '{
			   	 	"touser":"'.$openid.'",
			    	"msgtype":"text",
			    	"text":
			    	{
			        	"content":"'.$text.'"
			    	}
				}';
    	$this->access_token = $token == '' ? $this->access_token : $token;
    	if($this->access_token != '')
    	{
    		$url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$this->access_token;
    		$this->post_it($url, $data);
    	}
    }
    
    /**
     * 获取用户操作
     */
    public function getTextMsg()
	{
		$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
		if(!empty($postStr))
		{    
			$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
			$this->data=(array)$postObj; 
		}
	}
	
	/**
	 * 回复文本信息
	 * @param unknown $contentStr
	 * @param string $toUser
	 */
	public function replyTextMsg($contentStr, $toUser = '')
	{
		$msgType = "text";
		$time = yf_time();
		$ToUserName = $toUser == '' ? $this->data['FromUserName'] : $toUser;
        $textTpl = "<xml>
						<ToUserName><![CDATA[%s]]></ToUserName>
						<FromUserName><![CDATA[%s]]></FromUserName>
						<CreateTime>%s</CreateTime>
						<MsgType><![CDATA[%s]]></MsgType>
						<Content><![CDATA[%s]]></Content>
					</xml>";  
		$resultStr = sprintf($textTpl, $ToUserName, $this->data['ToUserName'], $time, $msgType, $contentStr);
        echo $resultStr;
	}
	
	/**
	 *回复图文信息 
	 * @param unknown $arr
	 */
	public function replyImgMsg($arr)
	{
		$msgType = "news";
		$ToUserName = $this->data['FromUserName'];
		$num = count($arr);
		$time = yf_time();
		$item = '';
       
		if($num > 0)
		{
			foreach($arr as $k=>$v)
		  	{
				$itemTpl = "<item>
								<Title><![CDATA[%s]]></Title> 
								<Description><![CDATA[%s]]></Description>
								<PicUrl><![CDATA[%s]]></PicUrl>
								<Url><![CDATA[%s]]></Url>
							</item>";
            	$item .= sprintf($itemTpl, $v['title'], $v['description'], "http://".$_SERVER['HTTP_HOST']."/".$v['thumb'], $v['url']);
		   	}
			$textTpl = "<xml>
							<ToUserName><![CDATA[%s]]></ToUserName>
							<FromUserName><![CDATA[%s]]></FromUserName>
							<CreateTime>%s</CreateTime>
							<MsgType><![CDATA[%s]]></MsgType>
							<ArticleCount>%s</ArticleCount>
							<Articles>".$item."</Articles>
						</xml>";   
            $resultStr = sprintf($textTpl, $ToUserName, $this->data['ToUserName'], $time, $msgType, $num);
            echo $resultStr; 
		}
	}
	
	/**
	 * 回复音乐消息
	 * @param $url
	 * @param $title
	 */
    public function replyMusicMsg($url, $title)
	{
		$msgType = "music";
		$time = time();
        $textTpl = "<xml>
        				<ToUserName><![CDATA[%s]]></ToUserName><FromUserName><![CDATA[%s]]></FromUserName>
						<CreateTime>%s</CreateTime>
						<MsgType><![CDATA[%s]]></MsgType>
						<Music>
							<Title><![CDATA[%s]]></Title>
							<Description><![CDATA[%s]]></Description>
							<MusicUrl><![CDATA[%s]]></MusicUrl>
							<HQMusicUrl><![CDATA[%s]]></HQMusicUrl>
						</Music>
        			</xml>";  
		$resultStr = sprintf($textTpl, $this->data['FromUserName'], $this->data['ToUserName'], $time, $msgType, $title,'希望你喜欢',$url,$url,'');
		echo $resultStr; 
	}
		
	/**
	 * 获取jsapi_ticket
	 */
	public function getJsapiTicket($access_token='')
	{
		if($access_token=='')
		{
			$access_token=$this->access_token;
		}
		$url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=$access_token&type=jsapi";
		$json = file_get_contents($url);//获取微信用户基本信息
		$arr = json_decode($json,true);
		return $arr;
	}
	
	/**
	 * 获取卡券api_ticket
	 */
	public function getCardapiTicket($access_token='')
	{
	    if($access_token=='')
	    {
	        $access_token=$this->access_token;
	    }
	    
	    $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=$access_token&type=wx_card";
// 	    $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=$access_token&type=jsapi";
	    $json = file_get_contents($url);//获取微信用户基本信息
	    $arr = json_decode($json,true);
	    return $arr;
	}
}